<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>糖糖宝宝喂奶记录</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  
  <!-- 配置 Tailwind CSS 自定义颜色和字体 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#4F9CFE',      // 柔和蓝色作为主色调
            secondary: '#FF9BB3',    // 温暖粉色作为辅助色
            urgent: '#FF6B6B',       // 紧急状态颜色
            warning: '#FFD166',      // 警告状态颜色
            normal: '#06D6A0',       // 正常状态颜色
            neutral: {
              100: '#F8FAFC',
              200: '#E2E8F0',
              300: '#CBD5E1',
              700: '#334155',
              800: '#1E293B',
              900: '#0F172A'
            }
          },
          fontFamily: {
            inter: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>
  
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .record-animation {
        animation: fadeIn 0.3s ease-in-out;
      }
      .bounce-in {
        animation: bounceIn 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
      }
      .slide-up {
        animation: slideUp 0.3s ease-out;
      }
      .shadow-soft {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      }
      .pulse {
        animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
      }
    }
    
    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(10px); }
      to { opacity: 1; transform: translateY(0); }
    }
    
    @keyframes bounceIn {
      0% { transform: scale(0.8); opacity: 0; }
      50% { transform: scale(1.05); }
      100% { transform: scale(1); opacity: 1; }
    }
    
    @keyframes slideUp {
      from { transform: translateY(20px); opacity: 0; }
      to { transform: translateY(0); opacity: 1; }
    }
    
    @keyframes pulse {
      0%, 100% { opacity: 1; }
      50% { opacity: 0.5; }
    }
    
    /* 时间间隔样式 */
    .time-interval {
      display: inline-flex;
      align-items: center;
      padding: 4px 10px;
      border-radius: 20px;
      font-weight: 600;
      font-size: 0.9rem;
    }
    
    .interval-short {
      background-color: rgba(255, 107, 107, 0.15);
      color: #FF6B6B;
    }
    
    .interval-medium {
      background-color: rgba(255, 209, 102, 0.15);
      color: #e6a200;
    }
    
    .interval-long {
      background-color: rgba(6, 214, 160, 0.15);
      color: #06D6A0;
    }
    
    /* 喂奶计时器样式 */
    .feeding-timer {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      text-align: center;
      padding: 15px;
      border-radius: 16px;
      background: linear-gradient(135deg, #4F9CFE 0%, #6C63FF 100%);
      color: white;
      box-shadow: 0 6px 16px rgba(79, 156, 254, 0.3);
    }
    
    /* 进度条样式 */
    .progress-container {
      height: 8px;
      background-color: rgba(255, 255, 255, 0.3);
      border-radius: 4px;
      overflow: hidden;
      margin-top: 12px;
      width: 100%;
    }
    
    .progress-bar {
      height: 100%;
      background-color: white;
      border-radius: 4px;
      transition: width 0.5s ease;
    }
    
    /* 自定义设置样式 */
    .setting-card {
      background-color: white;
      border-radius: 16px;
      padding: 20px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    }
    
    .slider-container {
      margin: 15px 0;
    }
    
    .slider {
      -webkit-appearance: none;
      height: 8px;
      border-radius: 5px;
      background: #d3d3d3;
      outline: none;
    }
    
    .slider::-webkit-slider-thumb {
      -webkit-appearance: none;
      appearance: none;
      width: 22px;
      height: 22px;
      border-radius: 50%;
      background: #4F9CFE;
      cursor: pointer;
    }
    
    .slider::-moz-range-thumb {
      width: 22px;
      height: 22px;
      border-radius: 50%;
      background: #4F9CFE;
      cursor: pointer;
      border: none;
    }
  </style>
</head>
<body class="font-inter bg-neutral-100 min-h-screen text-neutral-800">
  <!-- 顶部导航栏 -->
  <header class="bg-white shadow-soft sticky top-0 z-50 transition-all duration-300">
    <div class="container mx-auto px-4 py-4 flex justify-between items-center">
      <h1 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-primary flex items-center">
        <i class="fa fa-baby-bottle mr-2"></i>糖糖宝宝喂奶记录
      </h1>
      <div class="flex items-center space-x-2">
        <button id="settings-btn" class="text-neutral-700 hover:text-primary transition-colors duration-200">
          <i class="fa fa-cog text-lg"></i>
        </button>
        <button id="clear-all-btn" class="text-neutral-700 hover:text-red-500 transition-colors duration-200">
          <i class="fa fa-trash-o text-lg"></i>
        </button>
      </div>
    </div>
  </header>
  <main class="container mx-auto px-4 py-6">
    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8">
      <div class="bg-white rounded-xl p-5 shadow-soft bounce-in">
        <div class="flex items-center">
          <div class="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center text-primary mr-4">
            <i class="fa fa-clock-o text-xl"></i>
          </div>
          <div>
            <p class="text-neutral-500 text-sm">今日喂养次数</p>
            <p id="today-count" class="text-2xl font-bold">0</p>
          </div>
        </div>
      </div>
      
      <div class="bg-white rounded-xl p-5 shadow-soft bounce-in" style="animation-delay: 0.1s">
        <div class="flex items-center">
          <div class="w-12 h-12 rounded-full bg-secondary/10 flex items-center justify-center text-secondary mr-4">
            <i class="fa fa-tint text-xl"></i>
          </div>
          <div>
            <p class="text-neutral-500 text-sm">今日总奶量</p>
            <p id="today-milk" class="text-2xl font-bold">0 ml</p>
          </div>
        </div>
      </div>
      
      <div class="bg-white rounded-xl p-5 shadow-soft bounce-in" style="animation-delay: 0.2s">
        <div class="flex items-center">
          <div class="w-12 h-12 rounded-full bg-green-100 flex items-center justify-center text-green-600 mr-4">
            <i class="fa fa-history text-xl"></i>
          </div>
          <div>
            <p class="text-neutral-500 text-sm">最近喂养</p>
            <p id="last-feed" class="text-2xl font-bold">暂无记录</p>
          </div>
        </div>
      </div>
      
      <!-- 下次喂奶时间卡片 -->
      <div class="feeding-timer bounce-in" style="animation-delay: 0.3s">
        <div class="flex items-center mb-2">
          <i class="fa fa-clock-o text-xl mr-2"></i>
          <span class="text-sm font-medium">下次喂奶时间</span>
        </div>
        <p id="next-feed" class="text-xl font-bold mb-1">--:--</p>
        <p id="time-remaining" class="text-sm opacity-90">暂无数据</p>
        <div class="progress-container">
          <div id="progress-bar" class="progress-bar" style="width: 0%"></div>
        </div>
      </div>
    </div>
    <!-- 添加记录表单 -->
    <section class="bg-white rounded-xl p-6 shadow-soft mb-8 slide-up">
      <h2 class="text-xl font-semibold mb-4 text-neutral-800 flex items-center">
        <i class="fa fa-plus-circle text-primary mr-2"></i>添加喂养记录
      </h2>
      
      <form id="feed-form" class="space-y-4">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label for="date" class="block text-sm font-medium text-neutral-700 mb-1">日期</label>
            <input type="date" id="date" class="w-full px-3 py-2 border border-neutral-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all" value="" required>
          </div>
          
          <div>
            <label for="time" class="block text-sm font-medium text-neutral-700 mb-1">时间</label>
            <input type="time" id="time" class="w-full px-3 py-2 border border-neutral-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all" value="" required>
          </div>
        </div>
        
        <div>
          <label for="milk" class="block text-sm font-medium text-neutral-700 mb-1">奶量 (ml)</label>
          <div class="relative">
            <input type="number" id="milk" min="10" max="300" step="10" class="w-full px-3 py-2 border border-neutral-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all" placeholder="例如: 120" required>
            <div class="absolute right-3 top-1/2 transform -translate-y-1/2 text-neutral-400">ml</div>
          </div>
        </div>
        
        <button type="submit" class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-3 px-4 rounded-lg transition-all duration-300 flex items-center justify-center">
          <i class="fa fa-save mr-2"></i>保存记录
        </button>
      </form>
    </section>
    <!-- 记录列表 -->
    <section class="mb-8">
      <h2 class="text-xl font-semibold mb-4 text-neutral-800 flex items-center">
        <i class="fa fa-list-alt text-primary mr-2"></i>喂养记录列表
        <span id="record-count" class="ml-2 text-sm bg-neutral-200 text-neutral-700 px-2 py-1 rounded-full"></span>
      </h2>
      
      <div id="records-container" class="space-y-3">
        <!-- 记录将通过JavaScript动态添加到这里 -->
        <div class="text-center py-8 text-neutral-500" id="empty-state">
          <i class="fa fa-info-circle text-3xl mb-3 text-neutral-300"></i>
          <p>暂无喂养记录，点击"添加喂养记录"开始记录吧</p>
        </div>
      </div>
    </section>
  </main>
  <!-- 设置模态框 -->
  <div id="settings-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl p-6 max-w-md w-full mx-4 shadow-lg transform transition-all">
      <div class="flex justify-between items-center mb-6">
        <h3 class="text-xl font-semibold text-neutral-800">喂养设置</h3>
        <button id="close-settings" class="text-neutral-400 hover:text-neutral-700">
          <i class="fa fa-times text-lg"></i>
        </button>
      </div>
      
      <div class="setting-card mb-6">
        <h4 class="text-lg font-medium text-neutral-800 mb-4 flex items-center">
          <i class="fa fa-clock-o text-primary mr-2"></i>喂奶间隔设置
        </h4>
        <p class="text-neutral-600 text-sm mb-3">设置两次喂奶之间的时间间隔</p>
        
        <div class="slider-container">
          <input type="range" id="feeding-interval-slider" min="1" max="12" value="5" class="slider">
        </div>
        
        <div class="flex justify-between items-center">
          <span class="text-sm text-neutral-500">1小时</span>
          <span id="interval-value" class="font-medium text-primary">5小时</span>
          <span class="text-sm text-neutral-500">12小时</span>
        </div>
      </div>
      
      <div class="flex justify-end space-x-3">
        <button id="cancel-settings" class="px-4 py-2 border border-neutral-300 rounded-lg text-neutral-700 hover:bg-neutral-100 transition-colors">
          取消
        </button>
        <button id="save-settings" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
          保存设置
        </button>
      </div>
    </div>
  </div>
  <!-- 删除确认模态框 -->
  <div id="delete-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl p-6 max-w-md w-full mx-4 shadow-lg transform transition-all">
      <h3 class="text-xl font-semibold text-neutral-800 mb-4">确认删除</h3>
      <p class="text-neutral-600 mb-6">您确定要删除这条喂养记录吗？此操作不可撤销。</p>
      <div class="flex justify-end space-x-3">
        <button id="cancel-delete" class="px-4 py-2 border border-neutral-300 rounded-lg text-neutral-700 hover:bg-neutral-100 transition-colors">
          取消
        </button>
        <button id="confirm-delete" class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors">
          确认删除
        </button>
      </div>
    </div>
  </div>
  <!-- 音频元素 - 世上只有妈妈好 -->
  <audio id="reminder-audio" preload="auto">
    <source src="https://music.163.com/song/media/outer/url?id=200162.mp3" type="audio/mpeg">
    <!-- 备用音频源 -->
    <source src="https://example.com/世上只有妈妈好.mp3" type="audio/mpeg">
    您的浏览器不支持音频播放
  </audio>
  <!-- 底部版权信息 -->
  <footer class="bg-white border-t border-neutral-200 py-4 mt-8">
    <div class="container mx-auto px-4 text-center text-neutral-500 text-sm">
      <p>宝宝喂奶记录 © 2025 | 用心记录每一次成长</p>
    </div>
  </footer>
  <script>
    // 应用状态管理
    const appState = {
      records: [],
      selectedRecordId: null,
      nextFeedTimer: null,
      feedingInterval: 5 * 60 * 60 * 1000, // 默认5小时喂奶间隔(毫秒)
      isFeedingReminderPlaying: false // 标记提醒音乐是否正在播放
    };
    // DOM 元素
    const feedForm = document.getElementById('feed-form');
    const recordsContainer = document.getElementById('records-container');
    const emptyState = document.getElementById('empty-state');
    const deleteModal = document.getElementById('delete-modal');
    const cancelDelete = document.getElementById('cancel-delete');
    const confirmDelete = document.getElementById('confirm-delete');
    const clearAllBtn = document.getElementById('clear-all-btn');
    const todayCountEl = document.getElementById('today-count');
    const todayMilkEl = document.getElementById('today-milk');
    const lastFeedEl = document.getElementById('last-feed');
    const recordCountEl = document.getElementById('record-count');
    const nextFeedEl = document.getElementById('next-feed');
    const timeRemainingEl = document.getElementById('time-remaining');
    const progressBar = document.getElementById('progress-bar');
    const settingsModal = document.getElementById('settings-modal');
    const settingsBtn = document.getElementById('settings-btn');
    const closeSettings = document.getElementById('close-settings');
    const cancelSettings = document.getElementById('cancel-settings');
    const saveSettings = document.getElementById('save-settings');
    const feedingIntervalSlider = document.getElementById('feeding-interval-slider');
    const intervalValueEl = document.getElementById('interval-value');
    const reminderAudio = document.getElementById('reminder-audio');

    // 初始化应用
    function initApp() {
      loadRecords();
      loadSettings();
      renderRecords();
      updateStats();
      setupEventListeners();
      setFormDateTime();
      startNextFeedTimer();
    }

    // 设置表单日期时间为当前时间
    function setFormDateTime() {
      const now = new Date();
      const dateStr = now.toISOString().split('T')[0];
      const timeStr = now.toTimeString().slice(0, 5);
      
      document.getElementById('date').value = dateStr;
      document.getElementById('time').value = timeStr;
    }

    // 从本地存储加载记录
    function loadRecords() {
      try {
        const savedRecords = localStorage.getItem('babyFeedRecords');
        if (savedRecords) {
          appState.records = JSON.parse(savedRecords);
        }
      } catch (e) {
        console.error('加载记录失败:', e);
        appState.records = [];
      }
    }

    // 从本地存储加载设置
    function loadSettings() {
      try {
        const savedInterval = localStorage.getItem('feedingInterval');
        if (savedInterval) {
          const intervalHours = parseInt(savedInterval);
          if (!isNaN(intervalHours) && intervalHours >= 1 && intervalHours <= 12) {
            appState.feedingInterval = intervalHours * 60 * 60 * 1000;
            feedingIntervalSlider.value = intervalHours;
            updateIntervalDisplay(intervalHours);
          }
        }
      } catch (e) {
        console.error('加载设置失败:', e);
      }
    }

    // 保存设置到本地存储
    function saveSettingsToLocalStorage() {
      try {
        const intervalHours = parseInt(feedingIntervalSlider.value);
        localStorage.setItem('feedingInterval', intervalHours);
        appState.feedingInterval = intervalHours * 60 * 60 * 1000;
      } catch (e) {
        console.error('保存设置失败:', e);
      }
    }

    // 保存记录到本地存储
    function saveRecords() {
      try {
        localStorage.setItem('babyFeedRecords', JSON.stringify(appState.records));
      } catch (e) {
        console.error('保存记录失败:', e);
      }
    }

    // 添加新记录
    function addRecord(date, time, milk) {
      const newRecord = {
        id: Date.now().toString(),
        date,
        time,
        milk: parseInt(milk),
        timestamp: new Date(`${date}T${time}`).getTime()
      };
      
      appState.records.unshift(newRecord);
      saveRecords();
      renderRecords();
      updateStats();
      
      // 停止当前提醒音(如果正在播放)
      stopFeedingReminder();
      
      // 重新启动计时器
      startNextFeedTimer();
      
      // 滚动到新添加的记录
      const newRecordEl = document.getElementById(`record-${newRecord.id}`);
      if (newRecordEl) {
        newRecordEl.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
      }
    }

    // 删除记录
    function deleteRecord(id) {
      appState.records = appState.records.filter(record => record.id !== id);
      saveRecords();
      renderRecords();
      updateStats();
      closeDeleteModal();
      
      // 重新启动计时器
      startNextFeedTimer();
    }

    // 清空所有记录
    function clearAllRecords() {
      if (confirm('确定要清空所有喂养记录吗？此操作不可撤销。')) {
        appState.records = [];
        saveRecords();
        renderRecords();
        updateStats();
        
        // 停止计时器和提醒音
        stopFeedingReminder();
        if (appState.nextFeedTimer) {
          clearInterval(appState.nextFeedTimer);
          appState.nextFeedTimer = null;
        }
        
        nextFeedEl.textContent = '--:--';
        timeRemainingEl.textContent = '暂无数据';
        progressBar.style.width = '0%';
      }
    }

    // 计算两条记录之间的时间间隔
    function getTimeDifference(timestamp1, timestamp2) {
      const diffInMinutes = Math.abs(timestamp1 - timestamp2) / (1000 * 60);
      const diffInHours = Math.floor(diffInMinutes / 60);
      const remainingMinutes = Math.floor(diffInMinutes % 60);
      
      let intervalClass = 'interval-medium';
      if (diffInMinutes < 60) {
        intervalClass = 'interval-short';
      } else if (diffInMinutes > 4 * 60) {
        intervalClass = 'interval-long';
      }
      
      let displayText;
      if (diffInMinutes < 60) {
        displayText = `${Math.floor(diffInMinutes)} 分钟`;
      } else if (diffInHours < 24) {
        displayText = `${diffInHours} 小时`;
        if (remainingMinutes > 0) {
          displayText += ` ${remainingMinutes} 分钟`;
        }
      } else {
        const days = Math.floor(diffInHours / 24);
        displayText = `${days} 天 ${diffInHours % 24} 小时`;
      }
      
      return {
        text: displayText,
        class: intervalClass
      };
    }

    // 启动下次喂奶计时器
    function startNextFeedTimer() {
      // 清除现有计时器
      if (appState.nextFeedTimer) {
        clearInterval(appState.nextFeedTimer);
      }
      
      // 如果没有记录，则重置显示
      if (appState.records.length === 0) {
        nextFeedEl.textContent = '--:--';
        timeRemainingEl.textContent = '暂无数据';
        progressBar.style.width = '0%';
        return;
      }
      
      // 获取最近一次喂奶时间
      const lastFeed = appState.records[0];
      const lastFeedTime = lastFeed.timestamp;
      const nextFeedTime = lastFeedTime + appState.feedingInterval;
      
      // 更新显示
      updateNextFeedDisplay(nextFeedTime);
      
      // 每秒更新一次显示
      appState.nextFeedTimer = setInterval(() => {
        updateNextFeedDisplay(nextFeedTime);
      }, 1000);
    }

    // 更新下次喂奶时间显示
    function updateNextFeedDisplay(nextFeedTime) {
      const now = Date.now();
      const timeRemaining = nextFeedTime - now;
      
      if (timeRemaining <= 0) {
        nextFeedEl.textContent = '现在';
        nextFeedEl.classList.add('pulse');
        timeRemainingEl.innerHTML = '<i class="fa fa-exclamation-circle mr-1"></i>该喂奶了！';
        timeRemainingEl.classList.add('text-urgent', 'font-bold');
        progressBar.style.width = '100%';
        progressBar.style.backgroundColor = '#FF6B6B';
        
        // 播放喂奶提醒音乐
        playFeedingReminder();
        return;
      }
      
      // 停止提醒音(如果时间未到)
      stopFeedingReminder();
      
      nextFeedEl.classList.remove('pulse');
      timeRemainingEl.classList.remove('text-urgent', 'font-bold');
      
      // 格式化下次喂奶时间
      const nextDate = new Date(nextFeedTime);
      const hours = nextDate.getHours().toString().padStart(2, '0');
      const minutes = nextDate.getMinutes().toString().padStart(2, '0');
      nextFeedEl.textContent = `${hours}:${minutes}`;
      
      // 计算剩余时间
      const hoursRemaining = Math.floor(timeRemaining / (1000 * 60 * 60));
      const minutesRemaining = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60));
      
      let timeText;
      if (hoursRemaining > 0) {
        timeText = `${hoursRemaining} 小时 ${minutesRemaining} 分钟`;
      } else {
        timeText = `${minutesRemaining} 分钟`;
      }
      
      timeRemainingEl.textContent = `剩余 ${timeText}`;
      
      // 更新进度条
      const progress = Math.min(100, Math.max(0, 100 - (timeRemaining / appState.feedingInterval * 100)));
      progressBar.style.width = `${progress}%`;
      
      // 根据进度改变颜色
      if (progress > 80) {
        progressBar.style.backgroundColor = '#FF6B6B';
      } else if (progress > 60) {
        progressBar.style.backgroundColor = '#FFD166';
      } else {
        progressBar.style.backgroundColor = '#FFFFFF';
      }
    }

    // 播放喂奶提醒音乐
    function playFeedingReminder() {
      if (appState.isFeedingReminderPlaying) return;
      
      appState.isFeedingReminderPlaying = true;
      
      // 重置音频并播放
      reminderAudio.currentTime = 0;
      reminderAudio.play().catch(e => {
        console.error('播放提醒音乐失败:', e);
        console.log('尝试在用户交互后播放...');
        
        // 如果在自动播放时失败，提示用户点击播放
        alert('由于浏览器限制，无法自动播放音乐\n请点击"保存记录"按钮后，到达时间会自动播放提醒');
      });
      
      // 30秒后停止播放(避免音乐过长)
      setTimeout(stopFeedingReminder, 30000);
    }

    // 停止喂奶提醒音乐
    function stopFeedingReminder() {
      reminderAudio.pause();
      reminderAudio.currentTime = 0;
      appState.isFeedingReminderPlaying = false;
    }

    // 更新间隔显示
    function updateIntervalDisplay(hours) {
      intervalValueEl.textContent = `${hours}小时`;
    }

    // 渲染记录列表
    function renderRecords() {
      if (appState.records.length === 0) {
        recordsContainer.innerHTML = `
          <div class="text-center py-8 text-neutral-500" id="empty-state">
            <i class="fa fa-info-circle text-3xl mb-3 text-neutral-300"></i>
            <p>暂无喂养记录，点击"添加喂养记录"开始记录吧</p>
          </div>
        `;
        recordCountEl.textContent = '';
        return;
      }
      
      recordsContainer.innerHTML = '';
      recordCountEl.textContent = appState.records.length;
      
      appState.records.forEach((record, index) => {
        const previousRecord = index > 0 ? appState.records[index - 1] : null;
        let timeDifference = {
          text: '首次喂养',
          class: 'interval-long'
        };
        
        if (previousRecord) {
          timeDifference = getTimeDifference(record.timestamp, previousRecord.timestamp);
        }
        
        const recordEl = document.createElement('div');
        recordEl.id = `record-${record.id}`;
        recordEl.className = 'bg-white rounded-xl p-5 shadow-soft record-animation';
        recordEl.innerHTML = `
          <div class="flex flex-col md:flex-row md:items-center justify-between">
            <div class="mb-3 md:mb-0">
              <p class="text-neutral-500 text-sm">日期</p>
              <p class="text-lg font-medium">${record.date}</p>
            </div>
            <div class="mb-3 md:mb-0 md:ml-6">
              <p class="text-neutral-500 text-sm">时间</p>
              <p class="text-lg font-medium">${record.time}</p>
            </div>
            <div class="mb-3 md:mb-0 md:ml-6">
              <p class="text-neutral-500 text-sm">奶量</p>
              <p class="text-lg font-medium text-secondary">${record.milk} ml</p>
            </div>
            <div class="ml-auto">
              <p class="text-neutral-500 text-sm">距上次</p>
              <p class="text-lg font-medium flex items-center">
                <span class="time-interval ${timeDifference.class}">
                  <i class="fa fa-clock-o mr-1"></i>${timeDifference.text}
                </span>
              </p>
            </div>
          </div>
          <div class="mt-4 flex justify-end space-x-2">
            <button class="delete-record-btn text-neutral-400 hover:text-red-500 transition-colors" data-id="${record.id}">
              <i class="fa fa-trash-o"></i>
            </button>
          </div>
        `;
        
        recordsContainer.appendChild(recordEl);
      });
      
      // 添加删除按钮事件监听
      document.querySelectorAll('.delete-record-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
          appState.selectedRecordId = e.target.closest('.delete-record-btn').dataset.id;
          openDeleteModal();
        });
      });
    }

    // 更新统计信息
    function updateStats() {
      const today = new Date();
      const todayDate = today.toISOString().split('T')[0];
      
      const todayRecords = appState.records.filter(record => record.date === todayDate);
      const todayMilkTotal = todayRecords.reduce((sum, record) => sum + record.milk, 0);
      
      todayCountEl.textContent = todayRecords.length;
      todayMilkEl.textContent = `${todayMilkTotal} ml`;
      
      if (appState.records.length > 0) {
        const lastRecord = appState.records[0];
        lastFeedEl.textContent = `${lastRecord.date} ${lastRecord.time}`;
      } else {
        lastFeedEl.textContent = '暂无记录';
      }
    }

    // 打开删除确认模态框
    function openDeleteModal() {
      deleteModal.classList.remove('hidden');
      document.body.style.overflow = 'hidden';
    }

    // 关闭删除确认模态框
    function closeDeleteModal() {
      deleteModal.classList.add('hidden');
      document.body.style.overflow = '';
      appState.selectedRecordId = null;
    }

    // 打开设置模态框
    function openSettingsModal() {
      settingsModal.classList.remove('hidden');
      document.body.style.overflow = 'hidden';
    }

    // 关闭设置模态框
    function closeSettingsModal() {
      settingsModal.classList.add('hidden');
      document.body.style.overflow = '';
    }

    // 设置事件监听
    function setupEventListeners() {
      // 表单提交
      feedForm.addEventListener('submit', (e) => {
        e.preventDefault();
        const date = document.getElementById('date').value;
        const time = document.getElementById('time').value;
        const milk = document.getElementById('milk').value;
        
        if (date && time && milk) {
          addRecord(date, time, milk);
          feedForm.reset();
          setFormDateTime();
        }
      });
      
      // 设置相关事件
      settingsBtn.addEventListener('click', openSettingsModal);
      closeSettings.addEventListener('click', closeSettingsModal);
      cancelSettings.addEventListener('click', closeSettingsModal);
      saveSettings.addEventListener('click', () => {
        saveSettingsToLocalStorage();
        closeSettingsModal();
        
        // 如果有记录，重新计算下次喂奶时间
        if (appState.records.length > 0) {
          startNextFeedTimer();
        }
      });
      
      // 间隔滑块事件
      feedingIntervalSlider.addEventListener('input', () => {
        const hours = parseInt(feedingIntervalSlider.value);
        updateIntervalDisplay(hours);
      });
      
      // 取消删除
      cancelDelete.addEventListener('click', closeDeleteModal);
      
      // 确认删除
      confirmDelete.addEventListener('click', () => {
        if (appState.selectedRecordId) {
          deleteRecord(appState.selectedRecordId);
        }
      });
      
      // 清空所有记录
      clearAllBtn.addEventListener('click', clearAllRecords);
      
      // 点击模态框外部关闭
      deleteModal.addEventListener('click', (e) => {
        if (e.target === deleteModal) {
          closeDeleteModal();
        }
      });
      
      settingsModal.addEventListener('click', (e) => {
        if (e.target === settingsModal) {
          closeSettingsModal();
        }
      });
      
      // 窗口点击事件，用于导航栏滚动效果
      window.addEventListener('scroll', () => {
        const header = document.querySelector('header');
        if (window.scrollY > 10) {
          header.classList.add('py-2', 'shadow-md');
          header.classList.remove('py-4', 'shadow-soft');
        } else {
          header.classList.add('py-4', 'shadow-soft');
          header.classList.remove('py-2', 'shadow-md');
        }
      });
    }

    // 启动应用
    document.addEventListener('DOMContentLoaded', initApp);
  </script>
</body>
</html>
